import pygame
import random
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 460
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("洲了个洲")

# 颜色定义
BG_COLOR = (255, 255, 255)
COLORS = [
    (255, 0, 0),  # 红
    (0, 255, 0),  # 绿
    (0, 0, 255),  # 蓝
    (255, 255, 0),  # 黄
    (128, 0, 128),  # 紫
]

# 卡片尺寸和间距
CARD_WIDTH = 55
CARD_HEIGHT = 70
SPACING = 40

# 游戏区域布局
GRID_ROWS = 3
GRID_COLS = 3
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 150

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具设置 - 向右移动
ITEM_WIDTH = 50
ITEM_HEIGHT = 50
ITEM_LEFT = SCREEN_WIDTH - ITEM_WIDTH - 50  # 向右移动，原-390改为-50
ITEM_TOP = 60
item_count = 1  # 清空道具数量

# 新增：刷新卡设置 - 向右移动
REFRESH_ITEM_WIDTH = 50
REFRESH_ITEM_HEIGHT = 50
REFRESH_ITEM_LEFT = ITEM_LEFT - REFRESH_ITEM_WIDTH - 10  # 向右移动
REFRESH_ITEM_TOP = ITEM_TOP
refresh_item_count = 1  # 刷新道具数量

# 新增：删除卡设置 - 向右移动
DELETE_ITEM_WIDTH = 50
DELETE_ITEM_HEIGHT = 50
DELETE_ITEM_LEFT = REFRESH_ITEM_LEFT - DELETE_ITEM_WIDTH - 10  # 向右移动
DELETE_ITEM_TOP = ITEM_TOP
delete_item_count = 1  # 删除道具数量

# 撤销按钮设置 - 向右移动
UNDO_BUTTON_WIDTH = 50
UNDO_BUTTON_HEIGHT = 50
UNDO_BUTTON_LEFT = ITEM_LEFT  # 向右移动
UNDO_BUTTON_TOP = ITEM_TOP + ITEM_HEIGHT + 10
undo_count = 1  # 撤销按钮数量

# 洗牌按钮设置 - 向右移动
SHUFFLE_BUTTON_WIDTH = 50
SHUFFLE_BUTTON_HEIGHT = 50
SHUFFLE_BUTTON_LEFT = UNDO_BUTTON_LEFT  # 向右移动
SHUFFLE_BUTTON_TOP = UNDO_BUTTON_TOP + UNDO_BUTTON_HEIGHT + 10
shuffle_count = 1  # 洗牌按钮数量

# 按钮状态
BUTTON_STATE = {
    "START": "start",
    "RESTART": "restart",
    "EXIT": "exit"
}

# 按钮样式配置
BUTTON_COLOR = {
    "normal": (52, 152, 219),    # 正常状态颜色（蓝色）
    "hover": (41, 128, 185),     # 悬停状态颜色（深蓝色）
    "click": (231, 76, 60),      # 点击状态颜色（红色）
    "text": (255, 255, 255)      # 文本颜色
}

# 按钮尺寸与位置
START_BUTTON_POS = (SCREEN_WIDTH // 2 - 150, SCREEN_HEIGHT // 2 + 100)
RESTART_BUTTON_POS = (SCREEN_WIDTH // 2 - 150, SCREEN_HEIGHT // 2 + 50)
EXIT_BUTTON_POS = (SCREEN_WIDTH // 2 - 150, SCREEN_HEIGHT // 2 + 150)

# 游戏状态
GAME_STATE = "START"  # START, PLAYING, GAME_OVER, VICTORY

# 道具使用状态
using_delete_item = False  # 是否正在使用删除道具
selected_slot_index = -1  # 选中的槽位索引

# 加载背景图像
try:
    script_dir = os.path.dirname(os.path.abspath(__file__))
    image_folder = os.path.join(script_dir, "image")

    # 开始界面背景
    start_bg_path = os.path.join(image_folder, "kaishi.png")
    start_bg_img = pygame.image.load(start_bg_path)
    start_bg_img = pygame.transform.scale(start_bg_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
    print("开始界面背景图像加载成功")

    # 游戏背景
    game_bg_path1 = os.path.join(image_folder, "back.png")
    game_bg_path2 = os.path.join(image_folder, "back1.png")
    game_bg_img1 = pygame.image.load(game_bg_path1)
    game_bg_img1 = pygame.transform.scale(game_bg_img1, (SCREEN_WIDTH, SCREEN_HEIGHT))
    game_bg_img2 = pygame.image.load(game_bg_path2)
    game_bg_img2 = pygame.transform.scale(game_bg_img2, (SCREEN_WIDTH, SCREEN_HEIGHT))
    print("游戏背景图像加载成功")
    # 用于切换背景的标志
    current_background = 0
    # 背景切换的时间间隔（毫秒）
    BACKGROUND_SWITCH_INTERVAL = 200
    last_switch_time = pygame.time.get_ticks()
except Exception as e:
    print(f"背景图像加载失败: {e}")
    start_bg_img = None
    game_bg_img1 = None
    game_bg_img2 = None

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(5):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")

# 加载mask图像
try:
    mask_path = os.path.join(image_folder, "mask.png")
    mask_img = pygame.image.load(mask_path)
    mask_img = pygame.transform.scale(mask_img, (CARD_WIDTH, CARD_HEIGHT))
    print("mask图像加载成功")
except Exception as e:
    print(f"mask图像加载失败: {e}")
    mask_img = None

# 加载道具图像
try:
    item_path = os.path.join(image_folder, "daoju1.png")
    item_img = pygame.image.load(item_path)
    item_img = pygame.transform.scale(item_img, (ITEM_WIDTH, ITEM_HEIGHT))
    print("道具图像加载成功")
except Exception as e:
    print(f"道具图像加载失败: {e}")
    item_img = None

# 新增：加载刷新卡图像
try:
    refresh_item_path = os.path.join(image_folder, "daoju2.png")
    refresh_item_img = pygame.image.load(refresh_item_path)
    refresh_item_img = pygame.transform.scale(refresh_item_img, (REFRESH_ITEM_WIDTH, REFRESH_ITEM_HEIGHT))
    print("刷新卡图像加载成功")
except Exception as e:
    print(f"刷新卡图像加载失败: {e}")
    refresh_item_img = None

# 新增：加载删除卡图像
try:
    delete_item_path = os.path.join(image_folder, "daoju3.png")
    delete_item_img = pygame.image.load(delete_item_path)
    delete_item_img = pygame.transform.scale(delete_item_img, (DELETE_ITEM_WIDTH, DELETE_ITEM_HEIGHT))
    print("删除卡图像加载成功")
except Exception as e:
    print(f"删除卡图像加载失败: {e}")
    delete_item_img = None

# 加载撤销按钮图像
try:
    undo_button_path = os.path.join(image_folder, "daoju2.png")
    undo_button_img = pygame.image.load(undo_button_path)
    undo_button_img = pygame.transform.scale(undo_button_img, (UNDO_BUTTON_WIDTH, UNDO_BUTTON_HEIGHT))
    print("撤销按钮图像加载成功")
except Exception as e:
    print(f"撤销按钮图像加载失败: {e}")
    undo_button_img = None

# 加载洗牌按钮图像
try:
    shuffle_button_path = os.path.join(image_folder, "daoju3.png")
    shuffle_button_img = pygame.image.load(shuffle_button_path)
    shuffle_button_img = pygame.transform.scale(shuffle_button_img, (SHUFFLE_BUTTON_WIDTH, SHUFFLE_BUTTON_HEIGHT))
    print("洗牌按钮图像加载成功")
except Exception as e:
    print(f"洗牌按钮图像加载失败: {e}")
    shuffle_button_img = None

# 加载标题图像
try:
    title_path = os.path.join(image_folder, "title.png")
    title_img = pygame.image.load(title_path)
    title_img = pygame.transform.scale(title_img, (350, 120))
    print("标题图像加载成功")
except Exception as e:
    print(f"标题图像加载失败: {e}")
    title_img = None

# 加载胜利和失败图像
try:
    win_path = os.path.join(image_folder, "win.png")
    win_img = pygame.image.load(win_path)
    win_img = pygame.transform.scale(win_img, (300, 200))
    print("胜利图像加载成功")
except Exception as e:
    print(f"胜利图像加载失败: {e}")
    win_img = None

try:
    end_path = os.path.join(image_folder, "end.png")
    end_img = pygame.image.load(end_path)
    end_img = pygame.transform.scale(end_img, (300, 200))
    print("失败图像加载成功")
except Exception as e:
    print(f"失败图像加载失败: {e}")
    end_img = None


class Particle:
    def __init__(self, x, y, color, speed_x, speed_y, size, alpha, rotation):
        self.x = x
        self.y = y
        self.color = color
        self.speed_x = speed_x
        self.speed_y = speed_y
        self.size = size
        self.alpha = alpha
        self.rotation = rotation

    def update(self):
        self.x += self.speed_x
        self.y += self.speed_y
        self.size -= 0.2
        self.alpha -= 2  # 透明度逐渐降低
        self.rotation += 5  # 增加旋转效果
        if self.size <= 0 or self.alpha <= 0:
            return True
        return False

    def draw(self):
        surface = pygame.Surface((self.size, self.size), pygame.SRCALPHA)
        surface.set_alpha(self.alpha)
        pygame.draw.circle(surface, self.color, (self.size // 2, self.size // 2), self.size // 2)
        rotated_surface = pygame.transform.rotate(surface, self.rotation)
        rect = rotated_surface.get_rect(center=(self.x, self.y))
        screen.blit(rotated_surface, rect)


class MovingCard:
    def __init__(self, card_type, start_x, start_y, end_x, end_y):
        self.card_type = card_type
        self.x = start_x
        self.y = start_y
        self.end_x = end_x
        self.end_y = end_y
        self.speed = 12
        self.scale = 1.5  # 点击后更大的放大比例
        self.target_scale = 1.0  # 移动过程中不小于原始尺寸
        self.scale_speed = 0.02  # 缩放速度

    def update(self):
        if self.x != self.end_x:
            if self.x < self.end_x:
                self.x = min(self.x + self.speed, self.end_x)
            else:
                self.x = max(self.x - self.speed, self.end_x)
        if self.y != self.end_y:
            if self.y < self.end_y:
                self.y = min(self.y + self.speed, self.end_y)
            else:
                self.y = max(self.y - self.speed, self.end_y)

        if self.scale > self.target_scale:
            self.scale = max(self.scale - self.scale_speed, self.target_scale)

        return self.x == self.end_x and self.y == self.end_y

    def draw(self):
        if card_images:
            scaled_img = pygame.transform.scale(card_images[self.card_type],
                                                (int(CARD_WIDTH * self.scale), int(CARD_HEIGHT * self.scale)))
            screen.blit(scaled_img, (self.x - (scaled_img.get_width() - CARD_WIDTH) // 2,
                                     self.y - (scaled_img.get_height() - CARD_HEIGHT) // 2))
        else:
            scaled_width = int(CARD_WIDTH * self.scale)
            scaled_height = int(CARD_HEIGHT * self.scale)
            pygame.draw.rect(screen, COLORS[self.card_type],
                             (self.x - (scaled_width - CARD_WIDTH) // 2, self.y - (scaled_height - CARD_HEIGHT) // 2,
                              scaled_width, scaled_height))


class Button:
    def __init__(self, x, y, width, height, text, state, font_size=36):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.state = state  # 按钮状态（START/RESTART/EXIT）
        self.font = pygame.font.Font(None, font_size)
        self.hovered = False
        self.clicked = False

        # 按钮样式（使用全局配置）
        self.normal_color = BUTTON_COLOR["normal"]
        self.hover_color = BUTTON_COLOR["hover"]
        self.click_color = BUTTON_COLOR["click"]
        self.text_color = BUTTON_COLOR["text"]
        self.border_radius = 10
        self.shadow_offset = 3

    def is_hovered(self, pos):
        """检测鼠标是否悬停在按钮上"""
        return self.rect.collidepoint(pos)

    def update(self, pos):
        """更新按钮状态（悬停/点击）"""
        self.hovered = self.is_hovered(pos)

    def handle_event(self, event):
        """处理鼠标事件（点击触发）"""
        if event.type == pygame.MOUSEBUTTONDOWN and self.is_hovered(event.pos):
            self.clicked = True
            return self.state  # 返回按钮状态（用于事件分发）
        elif event.type == pygame.MOUSEBUTTONUP:
            self.clicked = False
        return None

    def draw(self, surface):
        """绘制按钮（带阴影和圆角）"""
        # 绘制阴影
        shadow_rect = self.rect.move(self.shadow_offset, self.shadow_offset)
        pygame.draw.rect(surface, (0, 0, 0, 50), shadow_rect, border_radius=self.border_radius)

        # 绘制按钮主体
        button_color = self.click_color if self.clicked else (self.hover_color if self.hovered else self.normal_color)
        pygame.draw.rect(surface, button_color, self.rect, border_radius=self.border_radius)

        # 绘制文本
        text_surface = self.font.render(self.text, True, self.text_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        surface.blit(text_surface, text_rect)


def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


def init_game():
    global grid, slots, score, game_over, game_won, moving_cards, particles, item_count, refresh_item_count, delete_item_count, using_delete_item, selected_slot_index, history
    # 初始化卡片堆
    grid = []
    for row in range(GRID_ROWS):
        grid_row = []
        for col in range(GRID_COLS):
            layers = random.randint(3, 7)
            max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
            stack = [random.randint(0, max_card_type) for _ in range(layers)]
            stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
            grid_row.append(stack)
        grid.append(grid_row)

    slots = []
    score = 0
    game_over = False
    game_won = False
    moving_cards = []
    particles = []
    item_count = 1
    refresh_item_count = 1
    delete_item_count = 1
    using_delete_item = False
    selected_slot_index = -1
    history = []  # 用于撤销操作的历史记录


def refresh_grid():
    """刷新网格中的卡片（重新排列）"""
    global grid

    # 收集所有卡片
    all_cards = []
    for row in grid:
        for stack in row:
            all_cards.extend(stack)

    # 打乱卡片顺序
    random.shuffle(all_cards)

    # 重新分配卡片到网格
    index = 0
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            layers = len(grid[row][col])
            grid[row][col] = all_cards[index:index + layers]
            index += layers

    # 确保所有堆栈至少有一个卡片
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            if not grid[row][col]:
                max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
                grid[row][col] = [random.randint(0, max_card_type)]


# 创建按钮实例
start_button = Button(*START_BUTTON_POS, 300, 60, "开始游戏", BUTTON_STATE["START"], 48)
restart_button = Button(*RESTART_BUTTON_POS, 300, 60, "再来一次", BUTTON_STATE["RESTART"], 48)
exit_button = Button(*EXIT_BUTTON_POS, 300, 60, "退出游戏", BUTTON_STATE["EXIT"], 48)

# 主循环
clock = pygame.time.Clock()
running = True
history = []  # 用于撤销操作的历史记录

# 定义道具名称
ITEM_NAMES = {
    'clear': '清空槽位',
    'refresh': '刷新卡片',
    'delete': '删除卡片',
    'undo': '撤销操作',
    'shuffle': '洗牌'
}

while running:
    mouse_pos = pygame.mouse.get_pos()
    button_action = None  # 记录按钮触发的动作

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif GAME_STATE == "START":
            button_action = start_button.handle_event(event)
        elif GAME_STATE in ["GAME_OVER", "VICTORY"]:
            button_action = restart_button.handle_event(event) or exit_button.handle_event(event)
        elif GAME_STATE == "PLAYING" and not game_over:
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = mouse_pos

                # 记录当前状态用于撤销
                if not using_delete_item:
                    history.append(([row.copy() for row in grid], slots.copy(), score))
                    if len(history) > 5:  # 只保留最近5步
                        history.pop(0)

                # 检查是否点击道具
                if ITEM_LEFT <= x <= ITEM_LEFT + ITEM_WIDTH and ITEM_TOP <= y <= ITEM_TOP + ITEM_HEIGHT:
                    if item_count > 0:
                        slots = []
                        item_count -= 1

                # 新增：检查是否点击刷新卡
                elif REFRESH_ITEM_LEFT <= x <= REFRESH_ITEM_LEFT + REFRESH_ITEM_WIDTH and REFRESH_ITEM_TOP <= y <= REFRESH_ITEM_TOP + REFRESH_ITEM_HEIGHT:
                    if refresh_item_count > 0:
                        refresh_grid()
                        refresh_item_count -= 1

                # 新增：检查是否点击删除卡
                elif DELETE_ITEM_LEFT <= x <= DELETE_ITEM_LEFT + DELETE_ITEM_WIDTH and DELETE_ITEM_TOP <= y <= DELETE_ITEM_TOP + DELETE_ITEM_HEIGHT:
                    if delete_item_count > 0:
                        using_delete_item = True

                # 如果正在使用删除卡，检查是否点击槽位中的卡片
                elif using_delete_item:
                    slot_index = (x - SLOT_LEFT) // (CARD_WIDTH + 5)
                    if 0 <= slot_index < len(slots):
                        del slots[slot_index]
                        delete_item_count -= 1
                        using_delete_item = False

                else:
                    # 计算点击位置
                    grid_col = (x - GRID_LEFT) // (CARD_WIDTH + SPACING)
                    grid_row = (y - GRID_TOP) // (CARD_HEIGHT + SPACING)
                    # 检查点击范围
                    if 0 <= grid_row < GRID_ROWS and 0 <= grid_col < GRID_COLS:
                        if len(grid[grid_row][grid_col]) > 0:
                            # 检查槽位是否已满（改为7块）
                            if len(slots) >= SLOT_COLS:
                                game_over = True
                                continue

                            # 取出顶层卡片
                            card = grid[grid_row][grid_col].pop()
                            start_x = GRID_LEFT + grid_col * (CARD_WIDTH + SPACING)
                            start_y = GRID_TOP + grid_row * (CARD_HEIGHT + SPACING) + (
                                len(grid[grid_row][grid_col])) * (
                                              CARD_HEIGHT // 12)
                            end_x = SLOT_LEFT + len(slots) * (CARD_WIDTH + 5)
                            end_y = SLOT_TOP
                            moving_cards.append(MovingCard(card, start_x, start_y, end_x, end_y))

    # 更新按钮状态
    if GAME_STATE == "START":
        start_button.update(mouse_pos)
    elif GAME_STATE in ["GAME_OVER", "VICTORY"]:
        restart_button.update(mouse_pos)
        exit_button.update(mouse_pos)

    # 处理按钮动作
    if button_action == BUTTON_STATE["START"]:
        init_game()
        GAME_STATE = "PLAYING"
    elif button_action == BUTTON_STATE["RESTART"]:
        init_game()
        GAME_STATE = "PLAYING"
    elif button_action == BUTTON_STATE["EXIT"]:
        running = False

    # 检查是否需要切换背景
    current_time = pygame.time.get_ticks()
    if GAME_STATE == "PLAYING" and current_time - last_switch_time > BACKGROUND_SWITCH_INTERVAL:
        current_background = 1 - current_background
        last_switch_time = current_time

    # 绘制界面
    if GAME_STATE == "START":
        # 绘制开始界面背景
        if start_bg_img:
            screen.blit(start_bg_img, (0, 0))
        else:
            # 如果没有背景图片，绘制渐变背景
            for i in range(SCREEN_HEIGHT):
                color = (255 - i // 3, 200 - i // 4, 200 - i // 4)
                pygame.draw.line(screen, color, (0, i), (SCREEN_WIDTH, i))

        # 绘制标题
        if title_img:
            screen.blit(title_img, (SCREEN_WIDTH // 2 - title_img.get_width() // 2, 150))
        else:
            font = pygame.font.Font(None, 72)
            text = font.render("洲了个洲", True, (255, 0, 0))
            screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, 150))

        # 绘制游戏说明
        font = pygame.font.Font(None, 28)
        instructions = [
            "将相同的三个卡片消除",
            "槽位满时游戏结束",
            "使用道具帮助通关"
        ]
        for i, line in enumerate(instructions):
            text = font.render(line, True, (0, 0, 0))
            screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, 320 + i * 40))

        # 新增：绘制道具说明
        if delete_item_img and refresh_item_img:
            instruction_y = 400
            if delete_item_img:
                screen.blit(delete_item_img, (SCREEN_WIDTH // 2 - 150, instruction_y))
                text = font.render("删除卡：移除槽位中的一个卡片", True, (0, 0, 0))
                screen.blit(text, (SCREEN_WIDTH // 2 - 100, instruction_y + 10))
                instruction_y += 60

            if refresh_item_img:
                screen.blit(refresh_item_img, (SCREEN_WIDTH // 2 - 150, instruction_y))
                text = font.render("刷新卡：重新排列所有卡片", True, (0, 0, 0))
                screen.blit(text, (SCREEN_WIDTH // 2 - 100, instruction_y + 10))

        # 绘制开始按钮
        start_button.draw(screen)

        # 绘制版本信息
        font = pygame.font.Font(None, 20)
        version_text = font.render("Version 1.0", True, (100, 100, 100))
        screen.blit(version_text, (SCREEN_WIDTH - version_text.get_width() - 20, SCREEN_HEIGHT - 30))

    elif GAME_STATE == "PLAYING":
        # 绘制游戏界面背景
        if game_bg_img1 and game_bg_img2:
            if current_background == 0:
                screen.blit(game_bg_img1, (0, 0))
            else:
                screen.blit(game_bg_img2, (0, 0))
        else:
            screen.fill(BG_COLOR)

        # 绘制卡片堆
        for row in range(GRID_ROWS):
            for col in range(GRID_COLS):
                x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
                y = GRID_TOP + row * (CARD_HEIGHT + SPACING)
                stack = grid[row][col]
                for index, card_type in enumerate(stack):
                    offset_y = index * (CARD_HEIGHT // 12)  # 调整重叠的偏移量
                    draw_y = y + offset_y
                    if card_images:
                        screen.blit(card_images[card_type], (x, draw_y))
                    else:
                        pygame.draw.rect(screen, COLORS[card_type], (x, draw_y, CARD_WIDTH, CARD_HEIGHT))
                    # 除了最上层卡片，其他卡片上方叠加mask图像
                    if index < len(stack) - 1 and mask_img:
                        screen.blit(mask_img, (x, draw_y))

        # 绘制槽位背景
        if slot_bg_img:
            screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
        else:
            pygame.draw.rect(screen, (200, 200, 200),
                             (SLOT_LEFT - 5, SLOT_TOP - 5,
                              slot_width + 10, SLOT_HEIGHT + 10),
                             border_radius=10)

        # 更新并绘制移动中的卡片
        finished_cards = []
        for card in moving_cards:
            if card.update():
                finished_cards.append(card)
                slots.append(card.card_type)
            card.draw()

        # 检查槽位中是否有三个相同的卡片并消除
        card_counts = {}
        for card in slots:
            card_counts[card] = card_counts.get(card, 0) + 1
        for card_type, count in card_counts.items():
            if count >= 3:
                # 消除三个相同的卡片
                slots_remaining = []
                remove_count = 0
                for card in slots:
                    if card == card_type and remove_count < 3:
                        remove_count += 1
                    else:
                        slots_remaining.append(card)
                slots = slots_remaining

                # 计算消除位置（槽位中间）
                elimination_x = SLOT_LEFT + slot_width // 2
                elimination_y = SLOT_TOP + CARD_HEIGHT // 2

                # 添加粒子效果
                score += 1
                for _ in range(80):
                    color = random.choice([
                        (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (128, 0, 128),
                        (255, 0, 255), (0, 255, 255), (255, 128, 0), (128, 128, 0), (0, 128, 128)
                    ])
                    speed_x = random.uniform(-8, 8)
                    speed_y = random.uniform(-8, 8)
                    size = random.randint(3, 8)
                    alpha = random.randint(100, 255)
                    rotation = random.randint(0, 360)
                    particles.append(
                        Particle(elimination_x, elimination_y, color, speed_x, speed_y, size, alpha, rotation))

        # 更新并绘制粒子
        particles_to_remove = []
        for particle in particles:
            if particle.update():
                particles_to_remove.append(particle)
            particle.draw()
        for particle in particles_to_remove:
            particles.remove(particle)

        # 移除已完成移动的卡片
        for card in finished_cards:
            moving_cards.remove(card)

        # 绘制槽位中已静止的卡片
        for i, card in enumerate(slots):
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            y = SLOT_TOP

            # 如果正在使用删除卡，高亮显示鼠标悬停的槽位
            if using_delete_item and SLOT_LEFT <= mouse_pos[0] <= SLOT_LEFT + slot_width and SLOT_TOP <= mouse_pos[
                1] <= SLOT_TOP + CARD_HEIGHT:
                hover_slot = (mouse_pos[0] - SLOT_LEFT) // (CARD_WIDTH + 5)
                if hover_slot == i:
                    pygame.draw.rect(screen, (255, 255, 0, 100), (x, y, CARD_WIDTH, CARD_HEIGHT), 3)

            if card_images:
                screen.blit(card_images[card], (x, y))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, y, CARD_WIDTH, CARD_HEIGHT))

        # 绘制道具
        if item_img:
            screen.blit(item_img, (ITEM_LEFT, ITEM_TOP))
            font = pygame.font.Font(None, 24)
            text = font.render(f"x{item_count}", True, (255, 0, 0))
            screen.blit(text, (ITEM_LEFT + ITEM_WIDTH + 5, ITEM_TOP + ITEM_HEIGHT // 2 - 10))

            # 绘制道具名称
            name_font = pygame.font.Font(None, 16)
            name_text = name_font.render(ITEM_NAMES['clear'], True, (0, 0, 0))
            name_x = ITEM_LEFT + (ITEM_WIDTH - name_text.get_width()) // 2
            name_y = ITEM_TOP + ITEM_HEIGHT + 5
            screen.blit(name_text, (name_x, name_y))

        # 新增：绘制刷新卡道具
        if refresh_item_img:
            screen.blit(refresh_item_img, (REFRESH_ITEM_LEFT, REFRESH_ITEM_TOP))
            font = pygame.font.Font(None, 24)
            text = font.render(f"x{refresh_item_count}", True, (255, 0, 0))
            screen.blit(text,
                        (REFRESH_ITEM_LEFT + REFRESH_ITEM_WIDTH + 5, REFRESH_ITEM_TOP + REFRESH_ITEM_HEIGHT // 2 - 10))

            # 绘制道具名称
            name_font = pygame.font.Font(None, 16)
            name_text = name_font.render(ITEM_NAMES['refresh'], True, (0, 0, 0))
            name_x = REFRESH_ITEM_LEFT + (REFRESH_ITEM_WIDTH - name_text.get_width()) // 2
            name_y = REFRESH_ITEM_TOP + REFRESH_ITEM_HEIGHT + 5
            screen.blit(name_text, (name_x, name_y))

        # 新增：绘制删除卡道具
        if delete_item_img:
            screen.blit(delete_item_img, (DELETE_ITEM_LEFT, DELETE_ITEM_TOP))
            font = pygame.font.Font(None, 24)
            text = font.render(f"x{delete_item_count}", True, (255, 0, 0))
            screen.blit(text,
                        (DELETE_ITEM_LEFT + DELETE_ITEM_WIDTH + 5, DELETE_ITEM_TOP + DELETE_ITEM_HEIGHT // 2 - 10))

            # 绘制道具名称
            name_font = pygame.font.Font(None, 16)
            name_text = name_font.render(ITEM_NAMES['delete'], True, (0, 0, 0))
            name_x = DELETE_ITEM_LEFT + (DELETE_ITEM_WIDTH - name_text.get_width()) // 2
            name_y = DELETE_ITEM_TOP + DELETE_ITEM_HEIGHT + 5
            screen.blit(name_text, (name_x, name_y))

        # 如果正在使用删除卡，显示提示
        if using_delete_item:
            font = pygame.font.Font(None, 28)
            text = font.render("点击槽位中的卡片进行删除", True, (255, 0, 0))
            screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, SLOT_TOP + CARD_HEIGHT + 20))

        # 绘制状态信息
        font = pygame.font.Font(None, 36)
        text = font.render(f"分数: {score}", True, (0, 0, 0))
        screen.blit(text, (20, 20))

        # 绘制槽位容量提示
        capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
        screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

        # 检查胜利条件
        if check_victory():
            game_won = True
            game_over = True

        if game_over:
            # 创建半透明覆盖层
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 150))
            screen.blit(overlay, (0, 0))

            # 绘制游戏结束/胜利信息
            if game_won and win_img:
                screen.blit(win_img, (SCREEN_WIDTH // 2 - win_img.get_width() // 2, SCREEN_HEIGHT // 2 - 150))
            elif not game_won and end_img:
                screen.blit(end_img, (SCREEN_WIDTH // 2 - end_img.get_width() // 2, SCREEN_HEIGHT // 2 - 150))
            else:
                font = pygame.font.Font(None, 60)
                text = font.render("胜利!" if game_won else "游戏结束!", True, (0, 255, 0) if game_won else (255, 0, 0))
                screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, SCREEN_HEIGHT // 2 - 100))

            # 绘制最终分数
            font = pygame.font.Font(None, 48)
            score_text = font.render(f"最终分数: {score}", True, (255, 255, 255))
            screen.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 30))

            # 绘制按钮
            restart_button.draw(screen)
            exit_button.draw(screen)

            if game_won:
                GAME_STATE = "VICTORY"
            else:
                GAME_STATE = "GAME_OVER"

    pygame.display.flip()
    clock.tick(90)

pygame.quit()